<template>
  <div id="login">
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm" @submit.native.prevent>
      <el-form-item label="账号" prop="pass">
        <el-input type="text" class = "username" v-model="ruleForm.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="checkPass">
        <el-input type="password" class="password" v-model="ruleForm.password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm()" native-type="submit">提交</el-button>
        <el-button @click="resetForm()">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        username: '',
        password: '',
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: 'blur' },
          {
            min:4,
            max:16,
            message: "用户名必须在4-16个字符之间",
            trigger: 'blur'
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 4,
            max: 16,
            message: '密码长度有误',
            trigger: 'blur'
          },
        ],
      },
    }
  },
  methods: {
    submitForm() {
      this.$refs.ruleForm.validate(async (valid) =>{
        if (!valid) return this.$message.error('输入非法，请重新输入')
        const {data : res} = await this.$http.post('/api/v1/login',this.ruleForm)
        if(res.code !== 200) return this.$message.error(res.message)
        window.sessionStorage.setItem('token', res.token)

        console.log(res.code, res.token)
        await this.$router.push('/admin')
      })
    },
    resetForm() {
      this.$refs.ruleForm.resetFields();
    }
  }
}
</script>

<style scoped>
  #login{
    padding-top: 100px;
    height: 300px;
    width: 500px;
    margin: 0 auto;
  }
  .username{
    width: 300px;
  }
  .password{
    width: 300px;
  }
</style>
